import React, { useEffect, useState } from 'react';
import { Input, Button, Table, Switch, Modal, notification, Space, } from 'antd'
import "../CXY/styles/systemtag.scss"
import { useNavigate } from 'react-router-dom';
import * as service from "../../../api/System"
import { PlusOutlined, CloseCircleOutlined } from '@ant-design/icons';
import ExportJsonExcel from "js-export-excel"
interface Props {

}
const { Search } = Input

function SystemTag(props: Props) {
    var navigate = useNavigate()
    const [isModalOpen, setIsModalOpen] = useState(false);
    var [pagination, setPagination] = useState({ current: 1, pageSize: 5, total: 0 });
    const [data, setData] = useState([])
    let [zt, setZt] = useState(true) // true 表示新增 false表示编辑
    var [id, setID] = useState()
    const [content, setContent] = useState('')
    useEffect(() => {
        getTitlelist()
    }, [])
    var getTitlelist = () => {
        service.title_list().then(res => {
            console.log(res)
            setData(res.data.data)
            setPagination({
                ...pagination,
                total: res.data.data.length
            })
        })
    }
    const myDelete = (row: any) => {
        console.log(row.labelId);
        console.log(typeof (row.labelId));
        Modal.confirm({
            icon: <CloseCircleOutlined style={{ color: "red" }} />,
            title: '删除标签',
            okText: '确认',
            cancelText: '取消',
            content: '确认要删除吗？',
            onOk() {
                service.title_delete({ labelId: row.labelId }).then((res) => {
                    console.log(res)
                    getTitlelist()
                    notification.success({
                        placement: "top",
                        message: "删除成功！"
                    })
                })
            },
        });

    }
    const columns = [
        {
            title: '编号',
            render: (_: any, record: never) => <a>{data.indexOf(record) + 1}</a>,//动态渲染标签/组件

        },
        {
            title: '标签名称',
            dataIndex: 'labelName',
            key: 'labelName',
        },
        {
            title: '添加人',
            dataIndex: 'journalName',
            key: 'journalName',
        },
        {
            title: '最后修改时间',
            dataIndex: 'labelTime',
            key: 'labelTime',
        },
        {
            title: '使用状态',
            render: (_: any, row: any) => {
                return (
                    <>
                        <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked={row.labelState} onChange={(value) => { changeCondition(row, value) }} />
                    </>
                )
            }
        },
        {
            title: '操作',
            render: (_: any, row: any) => {
                return (
                    <>
                        <span style={{ marginRight: 10, color: 'blue', cursor: "pointer" }} onClick={() => { edit(row) }}>编辑</span>
                        <span style={{ color: 'red', cursor: "pointer" }} onClick={() => { myDelete(row) }} >删除</span>
                    </>
                )
            }
        },
    ];

    const changeCondition = (row: any, value: any) => {
        service.title_condition({ labelId: row.labelId, labelState: value }).then((res1: any) => {
            console.log(res1);
            if (value == true) {
                notification.success({
                    placement: "top",
                    message: "已启用！"
                })
            } else {
                notification.success({
                    placement: "top",
                    message: "已禁用！"
                })
            }
        })
    };
    // 编辑
    const edit = (row: any) => {
        setZt(false)
        setIsModalOpen(true);
        setID(row.labelId)
        if (row.labelId) {
            console.log("编辑");
        } else {
            console.log("新增");

        }
    };
    const showModal = () => {
        setZt(true)
        setIsModalOpen(true);
    };

    var changeHandle = (e: any) => {
        setContent(e.target.value)
        // console.log(e.target.value);
    }

    let time = new Date()
    const handleOk = () => {
        console.log(zt)
        console.log(id);
        // console.log(content);
        if (!zt) {
            console.log(id);
            service.title_update({
                labelId: id,
                labelName: content,
                journalName: "李小萌",
                labelTime: time,
                labelState: true
            }).then((res) => {
                console.log("编辑", res);
                setIsModalOpen(false);
                if (res.data.code == 200) {
                    getTitlelist()
                    // navigate(0)
                    notification.success({
                        placement: "top",
                        message: "编辑成功！"
                    })
                }
            })
        } else {
            service.title_add({
                labelName: content,
                journalName: "李小萌",
                labelTime: time,
                labelState: true,
            }).then(res => {
                console.log("添加", res)
                getTitlelist()
                // navigate(0)
                setIsModalOpen(false);
                notification.success({
                    placement: "top",
                    message: "添加成功！"
                })
            })
        }
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    // 搜索
    const onSearch = (value: string) => {
        console.log(value);
        service.title_search({ labelName: value }).then((res) => {
            console.log(res);
            setData(res.data.data)
        })

    };
    // 分页
    const handleChange = (pagi: any) => {
        setPagination(pagi);//更新页码
    }
    let excel = () => {//导出Excel表
        let sheetFilter = ["labelId", "labelName", 'journalName', 'labelTime', 'labelState']//需要导出的属性，一般列表数据的属性
        let option = { fileName: "", datas: [{}] };
        option.fileName = "标签管理";
        option.datas = [
            {
                sheetData: data,//需要导出的数据
                sheetName: "居民列表",
                sheetFilter: sheetFilter,
                sheetHeader: ["编号", "标签名称", "添加人", "最后修改时间", "使用状态"],//每一列的列头
                columnWidth: [20, 20, 20, 20, 20],//每一列的宽
            }
        ]
        let toExcel = new ExportJsonExcel(option);
        toExcel.saveExcel();

    }
    return (
        <div className='system-tag'>
            <h4 className='title-system'>标签管理</h4>
            <div className='title-header' >
                <Search size="large" placeholder="请输入关键字" allowClear onSearch={onSearch} style={{ width: 400 }} />
                <Space>
                    <Button size="large" type="primary" onClick={showModal}>
                        新增标签
                    </Button>
                    <Button size="large" type="primary" onClick={excel}>
                        导出
                    </Button>
                </Space>
            </div>
            <Table
                columns={columns}
                dataSource={data}
                rowKey={(row: any) => row.labelId}
                pagination={pagination}
                onChange={(pagi) => { handleChange(pagi) }} />
            <Modal
                title="标签管理"
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                destroyOnClose={true}
            >
                标签名称：<Input placeholder="请输入" value={content} style={{ width: 200 }} onChange={(e) => changeHandle(e)} />
            </Modal>
        </div>
    );
}

export default SystemTag;